package com.itcam.kuangstudy.reflection_;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Author:Cammy.Wu
 * Date:2024-05-13
 * Description:
 */

// 动态的创建对象，通过反射
public class ReflectionDemo08 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 获得class类对象
        Class c1 = Class.forName("com.itcam.kuangstudy.reflection_.User");

        // 构造一个对象 TODO:实例化类对象
        User user1 = (User) c1.getDeclaredConstructor().newInstance();   // 本质是调用了类的无参构造器
        System.out.println("user1 = " + user1);

        // 通过构造器创建对象
//        Constructor constructor = c1.getDeclaredConstructor(int.class, String.class, int.class);
//        User user2 = (User) constructor.newInstance(007, "Cammy", 24);
//        System.out.println("user2 = " + user2);

        // 通过反射调用普通方法
        User user3 = (User) c1.getDeclaredConstructor().newInstance();
        // 通过反射获取一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);

        // invoke:激活的意思
        // (对象，“方法的值”)
        setName.invoke(user3, "Cammy1");
        System.out.println(user3.getName());

        // 通过反射操作属性
        System.out.println("########################");
        User user4 = (User) c1.getDeclaredConstructor().newInstance();
        Field name = c1.getDeclaredField("name");

        // 不能直接操作私有属性，需要关闭程序的安全检测，属性或者方法的setAccessible(true)
        name.setAccessible(true);
        name.set(user4, "Cammy2");
        System.out.println(user4.getName());

    }


}
